<template>
  <div class="container">
    <div id="canvasBox" :style="getStyle">
      <div class="greet">
        <span>请在下方空白处签名</span>
        <el-button @click="cancel">取消</el-button>
        <el-button @click="clear">清除</el-button>
        <el-button type="success" @click="finished">完成</el-button>
      </div>
      <canvas></canvas>
    </div>
  </div>
</template>
<script>
import Draw from '../utils/draw'
export default {
  name: 'autograph',
  data () {
    return {
      draw: null,
      degree: 90
    }
  },
  methods: {
    initCanvas () {
      const canvas = document.querySelector('canvas')
      this.draw = new Draw(canvas, -this.degree)
    },

    clear () {
      this.draw.clear()
    },

    finished () {
      this.$emit('success', this.draw.getPNGImage())
    },

    cancel () {
      this.$emit('cancel')
    }
  },
  mounted () {
    this.initCanvas()
  },
  computed: {
    getStyle () {
      const d = document
      const w = window.innerWidth || d.documentElement.clientWidth || d.body.clientWidth
      const h = window.innerHeight || d.documentElement.clientHeight || d.body.clientHeight
      let length = (h - w) / 2
      let width = w
      let height = h

      switch (this.degree) {
        case -90:
          length = -length
          break
        case 90:
          width = h
          height = w
          break
        default:
          length = 0
      }
      return {
        transform: `rotate(${this.degree}deg) translate(${length}px,${length}px)`, // rotate后需要translate以适应新的宽高
        width: `${width}px`,
        height: `${height}px`,
        transformOrigin: 'center center' // 指定旋转的中心
      }
    }
  }
}
</script>
<style lang="stylus">
.container, .image-box
  width 100%
  height 100%

#app
  position absolute
  top 0
  left 0
  right 0
  bottom 0
  font-family Avenir, Helvetica, Arial, sans-serif
  -webkit-font-smoothing antialiased
  -moz-osx-font-smoothing grayscale
  text-align center
  color #2c3e50

.greet a
  cursor pointer

#canvasBox
  display -webkit-box
  display -ms-flexbox
  display flex
  -webkit-box-orient vertical
  -webkit-box-direction normal
  -ms-flex-direction column
  flex-direction column
  height 100%

.greet
  padding 20px
  -webkit-user-select none
  -moz-user-select none
  -ms-user-select none
  user-select none

.greet, input
  font-size 20px

.greet select, .image-box header
  font-size 18px

canvas
  -webkit-box-flex 1
  -ms-flex 1
  flex 1
  cursor crosshair

.image-box img
  max-width 80%
  max-height 80%
  margin-top 50px
  border 1px solid gray
</style>
